﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;

namespace Rosetta.Default.AddIns.Xml
{
    public sealed class XElementConverter : Converter
    {
        #region Constructors

        public XElementConverter()
            : base("XElementConverter")
        {
            Category = "Xml";

            Add<XElement, IEnumerable<XElement>>("GetAllElements", GetAllElements, "element");
            Add<XElement, string, XAttribute>("GetAttribute", GetAttribute, "element", "name");
            Add<XElement, string, IEnumerable<XElement>>("GetElementsByName", GetElementsByName, "element", "name");
        }

        #endregion

        #region Class Methods

        private static IEnumerable<XElement> GetAllElements([NotNull] XElement element)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            return element.Elements();
        }

        private static XAttribute GetAttribute([NotNull] XElement element, [NotNull] string name)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            return element.Attribute(name);
        }

        private static IEnumerable<XElement> GetElementsByName([NotNull] XElement element, [NotNull] string name)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            return element.Elements(name);
        }

        #endregion
    }
}